/* $RCSFile: Monitoring.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Monitoring/Monitoring.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:21  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:57  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using System.IO;
using System.Text;

using System.Web.Mail;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Diagnostics;

using AddonNice.CRMWrapper;

using Telerik.Web.UI;
using Telerik.Charting;


using Trace2    =   System.Diagnostics.Trace;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;

namespace AddonNice.PageModules.Monitoring
{
        public class MNSTR
        {
		    public const string IgnoreFormating             =   "MONITORING_IGNORE_FORMATING";
		    public const string IgnorePaging                =   "MONITORING_IGNORE_PAGING";
		    public const string OpenInNewWindow             =   "MONITORING_OPENNEWWINDOW";
		    public const string AllowScrolling              =   "MONITORING_ALLOWSCROLLING";
		    public const string ScrollingHeight             =   "MONITORING_SCROLLHEIGHT";
            public const string SortedField                 =   "MONITORING_SORTEDFIELD";
            public const string Time                        =   "MONITORING_TIME";
            public const string Count                       =   "MONITORING_COUNT";
            public const string OptimizeGrid                =   "MONITORING_OPTIMIZE_GRID";
            public const string ChartWithZoom               =   "MONITORING_CHART_WITH_ZOOM";
            public const string DataTable                   =   "MONITORING_DATATABLE";
            public const string PageSize                    =   "MONITORING_PAGESIZE";
            public const string id                          =   "MONITORING_ID";
            public const string typecode                    =   "MONITORING_TYPECODE";
            public const string typename                    =   "MONITORING_TYPENAME";
            public const string webuserid                   =   "MONITORING_WEBUSERID";
            public const string webusername                 =   "MONITORING_WEBUSERNAME";
            public const string crmuserid                   =   "MONITORING_CRMUSERID";
            public const string crmusername                 =   "MONITORING_CRMUSERNAME";
            public const string portalid                    =   "MONITORING_PORTAL";
            public const string pageid                      =   "MONITORING_PAGEID";
            public const string moduleid                    =   "MONITORING_MODULEID";
            public const string itemid                      =   "MONITORING_ITEMID";
            public const string crmitemid                   =   "MONITORING_CRMITEMID";
            public const string crmitemname                 =   "MONITORING_CRMITEMNAME";
            public const string activitytime                =   "MONITORING_ACTIVITYTIME";
            public const string activitytype                =   "MONITORING_ACTIVITYTYPE";
            public const string referrer                    =   "MONITORING_URL_REFERER";
            public const string useragent                   =   "MONITORING_USERAGENT";
            public const string userhostaddress             =   "MONITORING_USERHOST";
            public const string browsertype                 =   "MONITORING_BROWSERTYPE";
            public const string browsername                 =   "MONITORING_BROWSERNAME";
            public const string browserversion              =   "MONITORING_BROWSERVERSION";
            public const string browserplatform             =   "MONITORING_BROWSERPLATFORM";
            public const string browserisaol                =   "MONITORING_BROWSERISAOL";
            public const string userfield                   =   "MONITORING_USERFIELD";
            public const string anonymous                   =   "MONITORING_ANONYMOUS";
            public const string isundercrm                  =   "MONITORING_UNDERCRM";
            
            
            public const string tabname                     =   "MONITORING_TABNAME";
            public const string username                    =   "MONITORING_USERNAME";
            public const string requests                    =   "MONITORING_REQUESTS";
            public const string lastrequest                 =   "MONITORING_LASTREQUEST";
            public const string actions                     =   "MONITORING_ACTIONS";
            public const string lastaction                  =   "MONITORING_LASTACTION";
            public const string date                        =   "MONITORING_DATE";
            public const string views                       =   "MONITORING_VIEWS";
            
            public const string visitors                    =   "MONITORING_VISITORS";
            public const string webusers                    =   "MONITORING_WEBUSERS";
            public const string crmusers                    =   "MONITORING_CRMUSERS";
            public const string days                        =   "MONITORING_DAYS";

            public const string strid                       =   "id";
            public const string strtypecode                 =   "typecode";
            public const string strtypename                 =   "typename"; // for SystemUser
            public const string strentitytypename           =   "entitytypename";
            public const string strcrmusername              =   "crmusername";
            public const string strwebusername              =   "webusername";
            public const string strcrmitemname              =   "crmitemname";
            public const string stranonymous                =   "anonymous";
            public const string strwebuserid                =   "userid";
            public const string strcrmuserid                =   "crmuserid";
            public const string strportalid                 =   "portalid";
            public const string strpageid                   =   "pageid";
            public const string strmoduleid                 =   "moduleid";
            public const string stritemid                   =   "itemid";
            public const string strcrmitemid                =   "crmitemid";
            public const string stractivitytime             =   "activitytime";
            public const string stractivitytype             =   "activitytype";
            public const string strreferrer                 =   "referrer";
            public const string struseragent                =   "useragent";
            public const string struserhostaddress          =   "userhostaddress";
            public const string strbrowsertype              =   "browsertype";
            public const string strbrowsername              =   "browsername";
            public const string strbrowserversion           =   "browserversion";
            public const string strbrowserplatform          =   "browserplatform";
            public const string strbrowserisaol             =   "browserisaol";
            public const string struserfield                =   "userfield";
            public const string strtabname                  =   "tabname";
            public const string strusername                 =   "username";
            public const string strrequests                 =   "requests";
            public const string strlastrequest              =   "lastrequest";
            public const string stractions                  =   "actions";
            public const string strlastaction               =   "lastaction";
            public const string strdate                     =   "date";
            public const string strviews                    =   "views";
            public const string strvisitors                 =   "visitors";
            public const string strwebusers                 =   "users";
            public const string strcrmusers                 =   "crmusers";
            public const string strdays                     =   "days";
            public const string strtime                     =   "time";
            public const string strcount                    =   "count";
        }

    /// <summary>
    /// Initializer class for Monitoring 
    /// </summary>
    public class MonitoringSI : PortalCRMModuleControlSI
    {
        public MonitoringSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MonitoringSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MonitoringSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MonitoringSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                   =   pm.ExtendedResourcesGroup;
            const string extgrp1            =   "MONITORING1";
            const string extgrp2            =   "MONITORING2";
			

            // Request fieds to display or not in grid
            SettingItemSpecial Field_id	    =	new SettingItemSpecial(MNSTR.id,new BooleanDataType());
			Field_id.Order			        =	20;
            Field_id.Value			        =	"True";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display id";
            Field_id.EnglishName		    =	MNSTR.id;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.typecode,new BooleanDataType());
			Field_id.Order			        =	30;
            Field_id.Value			        =	"True";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strtypecode;
            Field_id.EnglishName		    =	MNSTR.typecode;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.webuserid,new BooleanDataType());
			Field_id.Order			        =	40;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strwebuserid;
            Field_id.EnglishName		    =	MNSTR.webuserid;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.crmuserid,new BooleanDataType());
			Field_id.Order			        =	50;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strcrmuserid;
            Field_id.EnglishName		    =	MNSTR.crmuserid;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.portalid,new BooleanDataType());
			Field_id.Order			        =	60;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strportalid;
            Field_id.EnglishName		    =	MNSTR.portalid;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.pageid,new BooleanDataType());
			Field_id.Order			        =	70;
            Field_id.Value			        =	"True";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strpageid;
            Field_id.EnglishName		    =	MNSTR.pageid;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.moduleid,new BooleanDataType());
			Field_id.Order			        =	80;
            Field_id.Value			        =	"True";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strmoduleid;
            Field_id.EnglishName		    =	MNSTR.moduleid;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.itemid,new BooleanDataType());
			Field_id.Order			        =	90;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.stritemid;
            Field_id.EnglishName		    =	MNSTR.itemid;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.crmitemid,new BooleanDataType());
			Field_id.Order			        =	100;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strcrmitemid;
            Field_id.EnglishName		    =	MNSTR.crmitemid;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.activitytime,new BooleanDataType());
			Field_id.Order			        =	110;
            Field_id.Value			        =	"True";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.stractivitytime;
            Field_id.EnglishName		    =	MNSTR.activitytime;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.activitytype,new BooleanDataType());
			Field_id.Order			        =	120;
            Field_id.Value			        =	"True";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.stractivitytype;
            Field_id.EnglishName		    =	MNSTR.activitytype;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.referrer,new BooleanDataType());
			Field_id.Order			        =	130;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strreferrer;
            Field_id.EnglishName		    =	MNSTR.referrer;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.useragent,new BooleanDataType());
			Field_id.Order			        =	140;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.struseragent;
            Field_id.EnglishName		    =	MNSTR.useragent;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.userhostaddress,new BooleanDataType());
			Field_id.Order			        =	150;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.struserhostaddress;
            Field_id.EnglishName		    =	MNSTR.userhostaddress;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.browsertype,new BooleanDataType());
			Field_id.Order			        =	160;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strbrowsertype;
            Field_id.EnglishName		    =	MNSTR.browsertype;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.browsername,new BooleanDataType());
			Field_id.Order			        =	170;
            Field_id.Value			        =	"True";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strbrowsername;
            Field_id.EnglishName		    =	MNSTR.browsername;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.browserversion,new BooleanDataType());
			Field_id.Order			        =	180;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strbrowserversion;
            Field_id.EnglishName		    =	MNSTR.browserversion;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.browserplatform,new BooleanDataType());
			Field_id.Order			        =	190;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strbrowserplatform;
            Field_id.EnglishName		    =	MNSTR.browserplatform;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.browserisaol,new BooleanDataType());
			Field_id.Order			        =	200;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strbrowserisaol;
            Field_id.EnglishName		    =	MNSTR.browserisaol;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.userfield,new BooleanDataType());
			Field_id.Order			        =	210;
            Field_id.Value			        =	"False";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.struserfield;
            Field_id.EnglishName		    =	MNSTR.userfield;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.tabname,new BooleanDataType());
			Field_id.Order			        =	220;
            Field_id.Value			        =	"True";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strtabname;
            Field_id.EnglishName		    =	MNSTR.tabname;
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(MNSTR.username,new BooleanDataType());
			Field_id.Order			        =	230;
            Field_id.Value			        =	"True";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Should we display "+MNSTR.strusername;
            Field_id.EnglishName		    =	MNSTR.username;
			bSettings.AddSetting(Field_id);

            // Grid features : extgrp1

            SettingItemSpecial OptimizeGrid	        =	new SettingItemSpecial(MNSTR.OptimizeGrid,new BooleanDataType());
			OptimizeGrid.Order			            =	300;
            OptimizeGrid.Value			            =	StStr.strTrue;
			OptimizeGrid.ExtendedGroupName          =   extgrp1;
            OptimizeGrid.Group                      =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			OptimizeGrid.Description		        =	"Optimize Grid diplay";
            OptimizeGrid.EnglishName		        =	"When displaying large amout of data remove any unecessary function";
			bSettings.AddSetting(OptimizeGrid);

            SettingItemSpecial PageSz	            =	new SettingItemSpecial(MNSTR.PageSize,new IntegerDataType());
			PageSz.Order			                =	310;
            PageSz.Value			                =	"20";
			PageSz.ExtendedGroupName                =   extgrp1;
            PageSz.Group                            =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			PageSz.Description		                =	"Enter the grid page Size";
            PageSz.EnglishName		                =	"Page Size";
			bSettings.AddSetting(PageSz);

            
            SettingItemSpecial AllowScrolling	    =	new SettingItemSpecial(MNSTR.AllowScrolling,new BooleanDataType());
			AllowScrolling.Order			        =	315;
            AllowScrolling.Value			        =	StStr.strTrue;
			AllowScrolling.ExtendedGroupName        =   extgrp1;
            AllowScrolling.Group                    =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			AllowScrolling.Description		        =	"Allow scrolling for grid, else display as many rows as page size";
            AllowScrolling.EnglishName		        =	"Allow Scrolling";
			bSettings.AddSetting(AllowScrolling);

            SettingItemSpecial ScrollingHeight	    =	new SettingItemSpecial(MNSTR.ScrollingHeight,new UnitDataType());
			ScrollingHeight.Order			        =	318;
            ScrollingHeight.Value			        =	"500px";
			ScrollingHeight.ExtendedGroupName       =   extgrp1;
            ScrollingHeight.Group                   =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			ScrollingHeight.Description		        =	"When scrolling is enabled, height in pixel for scrolling window";
            ScrollingHeight.EnglishName		        =	"Scrolling Height";
			bSettings.AddSetting(ScrollingHeight);
            
            SettingItemSpecial IgnoreFormating      =   new SettingItemSpecial(MNSTR.IgnoreFormating,new BooleanDataType());
            IgnoreFormating.Required                =   false;
			IgnoreFormating.Order                   =   320;
            IgnoreFormating.Value                   =   StStr.strTrue;
			IgnoreFormating.ExtendedGroupName       =   extgrp1;
            IgnoreFormating.Group                   =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
            IgnoreFormating.EnglishName             =	"Ignore formating";
			IgnoreFormating.Description             =	"Ignore formating on export";
			bSettings.AddSetting(IgnoreFormating);           
            
            SettingItemSpecial IgnorePaging         =   new SettingItemSpecial(MNSTR.IgnorePaging,new BooleanDataType());
            IgnorePaging.Required                   =   false;
			IgnorePaging.Order                      =   330;
            IgnorePaging.Value                      =   StStr.strTrue;
			IgnorePaging.ExtendedGroupName          =   extgrp1;
            IgnorePaging.Group                      =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
            IgnorePaging.EnglishName                =	"Ignore paging";
			IgnorePaging.Description                =	"Ignore paging on export";
			bSettings.AddSetting(IgnorePaging);           
            
            SettingItemSpecial OpenInNewWindow      =   new SettingItemSpecial(MNSTR.OpenInNewWindow,new BooleanDataType());
            OpenInNewWindow.Required                =   false;
			OpenInNewWindow.Order                   =   340;
            OpenInNewWindow.Value                   =   StStr.strTrue;
			OpenInNewWindow.ExtendedGroupName       =   extgrp1;
            OpenInNewWindow.Group                   =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
            OpenInNewWindow.EnglishName             =	"Open in new window";
			OpenInNewWindow.Description             =	"Open in new window on export";
			bSettings.AddSetting(OpenInNewWindow);           
            
            // Chart features : extgrp2

            SettingItemSpecial ChartWithZoom	    =	new SettingItemSpecial(MNSTR.ChartWithZoom,new BooleanDataType());
			ChartWithZoom.Order			            =	400;
            ChartWithZoom.Value			            =	StStr.strFalse;
			ChartWithZoom.ExtendedGroupName         =   extgrp2;
            ChartWithZoom.Group                     =   SettingItemGroup.MODULE_SPECIAL_SETTINGS2;
			ChartWithZoom.Description		        =	"Chart with zoom";
            ChartWithZoom.EnglishName		        =	"Activate zooming on Charts";
			bSettings.AddSetting(ChartWithZoom);

            SettingItemSpecial GraphTb	            =	new SettingItemSpecial(MNSTR.DataTable,new BooleanDataType());
			GraphTb.Order			                =	410;
            GraphTb.Value			                =	StStr.strFalse;
			GraphTb.ExtendedGroupName               =   extgrp2;
            GraphTb.Group                           =   SettingItemGroup.MODULE_SPECIAL_SETTINGS2;
			GraphTb.Description		                =	"Should Graphs display data table";
            GraphTb.EnglishName		                =	"Graphs display datas";
			bSettings.AddSetting(GraphTb);

            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MonitoringSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

	/// <summary>
	/// AddonNice Monitoring Module - Shows website usage stats
	/// </summary>
	public partial class Monitoring : PortalCRMModuleControl
	{

        SortedList<Guid,string> CrmItems                    =   new SortedList<Guid,string>();
        SortedList<Guid,string> CrmUsers                    =   new SortedList<Guid,string>();

        string strAnonymous                                 =   LocalizeHelper.Localize(MNSTR.anonymous,MNSTR.stranonymous);

        /// <summary>
        /// No entity needed here
        /// </summary>
        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

        #region General Implementation

        public override bool AdminModule
		{
			get
			{
				return true;
			}
		}

		public override Guid GuidID 
		{
			get
			{
				return new Guid("{3B8E3585-58B7-4f56-8AB6-C04A2BFA6589}");
			}
		}
        #endregion General Implementation

        #region properties

        /// <summary>
        /// Last Cache key
        /// </summary>
        string LastKey
        {
            get
            {
                object ob   =   ViewState["LastKey"];
                if ( ob != null )
                    return (string)ob;
                return string.Empty;
            }
            set
            {
                ViewState["LastKey"] = value;
            }
        }

        /// <summary>
        /// Just for current request: positionned when any redraw is requested and apply in prereder when all fields has been updated
        /// </summary>
        bool _ShoudlRebind  =   false;
        bool ShoudlRebind
        {
            get
            {
                return _ShoudlRebind;
            }
            set
            {
                _ShoudlRebind = value;
            }
        }
        
        bool _ChangeGraphType  =   false;
        bool ChangeGraphType
        {
            get
            {
                return _ChangeGraphType;
            }
            set
            {
                _ChangeGraphType = value;
            }
        }
        #endregion properties

        #region Ctor and Initializer

        public Monitoring()
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose || MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring Ctor BEG.",( ModuleTraceSwitch.Sw.TraceVerbose ) ? ModuleTraceSwitch.Sw.Info:MonitoringTrace.Sw.Info);

            if ( ModuleTraceSwitch.Sw.TraceVerbose || MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring Ctor END.",( ModuleTraceSwitch.Sw.TraceVerbose ) ? ModuleTraceSwitch.Sw.Info:MonitoringTrace.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
       			const string extgrp             =   "MONITORING";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new MonitoringSI(bSettings,this);
        }

        #endregion Ctor 

        /// <summary>
		/// The Page_Load event handler on this User Control is used to
		/// determine sort field and order, and then databind the required
		/// monitoring table rows, generating a graph if necessary.
		/// Initial Revision by Paul Yarrow, paul@paulyarrow.com, 2003-07-13
		/// </summary>
		protected void Monitoring_Load(object sender, System.EventArgs e)
		{
            bool IsMonitoringEnabled        =   Config.IsMonitoringEnabled;
            if ( ModuleTraceSwitch.Sw.TraceVerbose || MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring Monitoring_Load BEG IsMonitoringEnabled: {0}, IsPostBack: {1}",
                    IsMonitoringEnabled,IsPostBack),( ModuleTraceSwitch.Sw.TraceVerbose ) ? ModuleTraceSwitch.Sw.Info:MonitoringTrace.Sw.Info);
			if(!IsMonitoringEnabled)
			{
				ErrorLabel.Text			    =   LocalizeHelper.Localize("SITE_MONITORING_DISABLED","Monitoring is disabled. Put EnableMonitoring to true in web.config.");
				RadTabStrip1.Visible        =   false;
				RadMultiPage1.Visible       =   false;
				ErrorLabel.Visible		    =   true;
				return;
			}
            
            // NOT OK ??? to have ajaxloadingpanel during ajaxrequest
            AddAjaxSetting(AjaxManager,AjaxManager);
            AddAjaxSetting(AjaxManager,RadTabStrip1);
            AddAjaxSetting(AjaxManager,RadMultiPage1);
            AddAjaxSetting(AjaxManager,FD2);
            // Set the variables correctly depending
			// on whether this is the first page view
			if (!IsPostBack) 
			{
                TBIpAddresses.Text          =   HttpContext.Current.Request.UserHostAddress;
                ArrayList skinsList         =   new ArrayList();
                skinsList.AddRange(new string[] { "Black", "Default", "Hay", "Inox", "Office2007", "Outlook", "Sunset", "Telerik", "Vista", "Web20", "WebBlue", "Marble", "Metal", "Wood", "BlueStripes", "DeepBlue", "DeepGray", "DeepGreen", "DeepRed", "GrayStripes", "GreenStripes", "LightBlue", "LightBrown", "LightGreen" } );
                ThumbList.DataSource        =   skinsList;
                ThumbList.DataBind();

                RadDateStart.SelectedDate   =   DateTime.Now.AddDays(-6);
                RadDateStart.Culture        =   System.Threading.Thread.CurrentThread.CurrentCulture;
                RadDateEnd.Culture          =   System.Threading.Thread.CurrentThread.CurrentCulture;
                RadDateEnd.SelectedDate     =   DateTime.Now;
                RadGrid1.PageSize           =   Settings[MNSTR.PageSize].ToInt();
                // according authentication mode allow searching on web/windows users
                bool isWin                  =   (Config.AuthenticationMode == System.Web.Configuration.AuthenticationMode.Windows);
                if (isWin)
                {
                    string txt              =   LocalizeHelper.Localize("MONITORING_MOSTACTIVECRMUSERS", "Most Active Crm users");
                    RadComboBoxItem it      =   new RadComboBoxItem(txt,"7");
                    cboReportType.Items.Add(it);
                }
                else
                {
                    string txt              =   LocalizeHelper.Localize("MONITORING_MOSTACTIVE_LOG", "Most Active Web users");
                    RadComboBoxItem it      =   new RadComboBoxItem(txt,"2");
                    cboReportType.Items.Add(it);
                }
                cboReportType.DataBind();
                // install graph type corresponding to Detailled Log
                RadComboBoxItem it1         =   new RadComboBoxItem("Area", ((int)ChartSeriesType.Area).ToString());
                it1.Selected                =   true;
                CbGraphType.Items.Add(it1);
                CbGraphType.DataBind();
                DivCrmItem.Visible          =   false;
                // init Grid for Detailled log
                InitGridParam0();
            }
		}

        void CheckedList1_SelectedIndexChanged(object sender, EventArgs e)
        {
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring CheckedList1_SelectedIndexChanged BEG RadGrid1.DataSource != null : {0}, sender: {1}.",
                    (RadGrid1.DataSource != null),sender ),MonitoringTrace.Sw.Info);
			ShoudlRebind        =   true;
            if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring CheckedList1_SelectedIndexChanged END.",MonitoringTrace.Sw.Info);
        }

        void CbGraphType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring CbGraphType_SelectedIndexChanged BEG OldChartType: {0}, new ChartType: {1}",e.OldValue,e.Value),MonitoringTrace.Sw.Info);
            ChangeGraphType     =   true;
            ShoudlRebind        =   true;
        }

        string curTheme         =   string.Empty;
        void ThumbList_ItemDataBound(object sender,RadComboBoxItemEventArgs e)
        {
            e.Item.ImageUrl     =   string.Format("/App_Themes/CommonImg/ChartThumbnails/{0}.gif", e.Item.Value);
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring ThumbList_ItemDataBound BEG e.Item.ImageUrl: {0}",e.Item.ImageUrl),MonitoringTrace.Sw.Info);
            if ( curTheme  == string.Empty)
                curTheme        =   this.ADNPage.Theme;
            if ( curTheme.IndexOf(e.Item.Value) > -1 )
            {
                e.Item.Selected =   true;
			    if ( MonitoringTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring ThumbList_ItemDataBound selected: {0}",e.Item.Value),MonitoringTrace.Sw.Info);
            }
        }

        void ThumbList_SelectedIndexChanged(object o,RadComboBoxSelectedIndexChangedEventArgs e)
        {
            RadChart1.Skin = ThumbList.SelectedValue;
            ChangeGraphType =   true;
            ShoudlRebind    =   true;
        }


        /// <summary>
        /// Refresh button clicked: flag a rebind which will be checked in PreRender 
        /// </summary>
        void BtnRefresh_Click(object sender,ImageClickEventArgs e)
        {
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring BtnRefresh_Click BEG cboReportType: {0}",cboReportType.SelectedItem.Text),MonitoringTrace.Sw.Info);
            ShoudlRebind    =   true;
        }

        /// <summary>
        /// Clear cache
        /// </summary>
        void BtnReset_Click(object sender,ImageClickEventArgs e)
        {
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring BtnReset_Click BEG.",MonitoringTrace.Sw.Info);
            LastKey         =   string.Empty;
            Cache2.RemoveAll("MonitorData_");
            ShoudlRebind    =   true;
            ChangeGraphType =   true;
        }

        /// <summary>
        /// Report Type changed: adapt grid and graph selections and rebind
        /// </summary>
        void cboReportType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring cboReportType_SelectedIndexChanged BEG SelectedItem: {0}",cboReportType.SelectedItem.Value),MonitoringTrace.Sw.Info);
			int reportType  =   int.Parse(e.Value);
            switch (reportType)
			{
				case 8:
				case 9:
				case 0:
                    InitGridParam0();
					break;

				default:
                    RadGrid1.AllowCustomPaging                                  =   false;
					RadGrid1.VirtualItemCount                                   =   0;
                    RadGrid1.ShowGroupPanel                                     =   false;
                    RadGrid1.AllowFilteringByColumn                             =   false; 
                    RadGrid1.ClientSettings.AllowDragToGroup                    =   false;
                    RadGrid1.ClientSettings.Scrolling.AllowScroll               =   Settings[MNSTR.AllowScrolling].ToBool();
                    if ( RadGrid1.ClientSettings.Scrolling.AllowScroll )
                        RadGrid1.ClientSettings.Scrolling.ScrollHeight          =   Settings[MNSTR.ScrollingHeight].ToUnit();
                    //RadGrid1.ClientSettings.Scrolling.EnableVirtualScrollPaging =   false;
					break;
            }
           
            DivCrmItem.Visible                                                  =   false;
            CheckedList1.Visible                                                =   false;
			switch (reportType)
			{
                case 8:
                    DivCrmItem.Visible                                          =   true;
                break;
				case 2:
				case 0:
                    CheckedList1.Visible                                        =   true;
					break;
				default:
					break;
            }
            // Second pass for filling graph types
            CbGraphType.ClearSelection();
            CbGraphType.Items.Clear();
            switch (reportType)
			{
                // Host detail
                case 9:
                // detailled Crm items viewed 
				case 8:
				//case "Detailed Site Log":
                case 0:
                    {
                        RadComboBoxItem it  =   new RadComboBoxItem("Area", ((int)ChartSeriesType.Area).ToString());
                        CbGraphType.Items.Add(it);
                        it.Selected         = true;
                    }
                    break;

				//case "Page Popularity":
                case 1:
                //case "Most Active Web Users":
                case 2:
				//case "Page Views By Browser Type":
				case 6:
				//case "Most Active Crm Users":
                case 7:
                    {
                        RadComboBoxItem it  =   new RadComboBoxItem("Pie", ((int)ChartSeriesType.Pie).ToString());
                        CbGraphType.Items.Add(it);
                        CbGraphType.Items.Add(new RadComboBoxItem("Bar", ((int)ChartSeriesType.Bar).ToString()));
                        it.Selected         =   true;
                    }
                    break;

                // most viewed items
                case 3:
                // most viewed Crm items
				case 4:
                //case "Page Views By Day":
				case 5:
                    {
                        RadComboBoxItem it  =   new RadComboBoxItem("Bar", ((int)ChartSeriesType.Bar).ToString());
                        CbGraphType.Items.Add(it);
                        CbGraphType.Items.Add(new RadComboBoxItem("Pie", ((int)ChartSeriesType.Pie).ToString()));
                        it.Selected         =   true;
                    }
                    break;
            }
            CbGraphType.DataBind(); // force rebind to install selected value
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring cboReportType_SelectedIndexChanged before Rebind CbGraphType.SelectedIndex: {0}",CbGraphType.SelectedIndex),MonitoringTrace.Sw.Info);
            ChangeGraphType =   true;
            ShoudlRebind    =   true;
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring cboReportType_SelectedIndexChanged END.",MonitoringTrace.Sw.Info);
		}

        void AjaxManager_AjaxRequest(object sender,AjaxRequestEventArgs e)
        {
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring AjaxManager_AjaxRequest argument: {0}",e.Argument),MonitoringTrace.Sw.Info);
            string dims             =   e.Argument;
            string[] sz             =   dims.Split(new char[]{','});
            if ( sz[0].IndexOf("px") == -1 )
                    sz[0]=sz[0]+"px";
            if ( sz[1].IndexOf("px") == -1 )
                    sz[1]=sz[1]+"px";
            if ( sz.Length > 1 )
            {
                RadChart1.Clear();
                RadChart1.Width     =   new Unit(sz[0]);
                RadChart1.Height    =   new Unit(sz[1]);
			    if ( MonitoringTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring AjaxManager_AjaxRequest Width: {0}, Height: {1}.",RadChart1.Width,RadChart1.Height),MonitoringTrace.Sw.Info);
                ChangeGraphType     =   true;
                ShoudlRebind        =   true;
            }
        }


        void InitExport()
		{
            RadGrid1.ExportSettings.ExportOnlyData  =   Settings[MNSTR.IgnoreFormating].ToBool();
            RadGrid1.ExportSettings.IgnorePaging    =   Settings[MNSTR.IgnorePaging].ToBool();
            RadGrid1.ExportSettings.OpenInNewWindow =   Settings[MNSTR.OpenInNewWindow].ToBool();
        }
		protected void BtnExport2XL()
		{
            InitExport();
            RadGrid1.MasterTableView.ExportToExcel();
        }

		protected void BtnExport2Wrd()
		{
            InitExport();
            RadGrid1.MasterTableView.ExportToWord();
        }
  
		protected void BtnExport2Pdf()
		{
            InitExport();
            RadGrid1.MasterTableView.ExportToPdf();
        }
  
        protected void BtnExport2Csv()
		{
            InitExport();
            RadGrid1.MasterTableView.ExportToCSV();
        }

        void ReBind()
        {
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring ReBind BEG.",MonitoringTrace.Sw.Info);
            RadGrid1.MasterTableView.CurrentPageIndex   =   0;
            RadGrid1.DataSource                         =   null;
            RadGrid1.Rebind();
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring ReBind END.",MonitoringTrace.Sw.Info);
		}

        void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring RadGrid1_NeedDataSource BEG RebindReason: {0}",e.RebindReason),ModuleTraceSwitch.Sw.Info);
			if ( RadDateStart.SelectedDate != null &&
                RadDateEnd.SelectedDate != null &&
                RadDateStart.SelectedDate <= RadDateEnd.SelectedDate )
            {
				// Read in the data regardless
				MonitoringDB monitorDB	    =   new MonitoringDB();

				DateTime startDate		    =   (DateTime)RadDateStart.SelectedDate;
				DateTime endDate		    =   (DateTime)RadDateEnd.SelectedDate;
                int ReportType              =   int.Parse(cboReportType.SelectedItem.Value);
                int SelectId                =   portalSettings.ActivePageSettings.PageID;
                string ipAddresses          =   TBIpAddresses.Text.Trim();
                if ( string.IsNullOrEmpty(ipAddresses) )
                    ipAddresses             =   HttpContext.Current.Request.UserHostAddress;
                // Here we replace currentPage by ItemCRMID
                if ( ReportType == 8 )
                {
                    string tpName           =   RadComboCrmItemType.SelectedItem.Value;
                    SelectId                =   (int)CRMWrapper.CRMUtil.typeCode(tpName);
                }
			    if ( MonitoringTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring RadGrid1_NeedDataSource ReportType: {0}, SelectId: {1}.",ReportType,SelectId),ModuleTraceSwitch.Sw.Info);
				try
				{
					string key              =   string.Format("MonitorData_{0}_{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8}_{9}_{10}_{11}_{12}_{13}",
                                                    new object[]{startDate,
						                                            endDate,
						                                            ReportType,
						                                            SelectId,
						                                            CheckedList1.Items[3].Selected ,// IncludeMonitorPage
						                                            CheckedList1.Items[0].Selected ,// PageRequests.Checked,
						                                            CheckedList1.Items[1].Selected ,// Logons.Checked,
						                                            CheckedList1.Items[2].Selected ,// Logouts.Checked,
						                                            CheckedList1.Items[4].Selected ,//  IncludeCallBack
						                                            CheckedList1.Items[5].Selected ,// CheckCrawlers.Checked,
						                                            CheckedList2.Items[0].Selected ,// IncludeMyIPAddress.Checked,
						                                            CheckedList2.Items[1].Selected ,// IncludeMyIPAddress.Checked,
                                                                    ipAddresses,
						                                            portalSettings.PortalID});
					DataTable monitorData	=   null;
                    bool redraw             =   true;
                    if ( MonitoringTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring RadGrid1_NeedDataSource LastKey: {0}, Key: {1}",LastKey,key),MonitoringTrace.Sw.Info);
                    if ( Cache2.Exists(key) )
                    {
                        if ( key == LastKey )
                            redraw          =   ChangeGraphType;
                        else LastKey        =   key;
                        monitorData         =   (DataTable)Cache2.Get(key);
                    }
                    else
                    {
                        LastKey             =   key;
                        monitorData         =   monitorDB.GetMonitoringStats(startDate,
                                                    endDate,
                                                    ReportType,0,
                                                    SelectId,
                                                    CheckedList1.Items[3].Selected,// IncludeMonitorPage
                                                    true,
                                                    CheckedList1.Items[0].Selected,// PageRequests.Checked,
                                                    CheckedList1.Items[1].Selected,// Logons.Checked,
                                                    CheckedList1.Items[2].Selected,// Logouts.Checked,
                                                    CheckedList2.Items[0].Selected,// IncludeMyIPAddress.Checked,
                                                    CheckedList2.Items[1].Selected,// IncludeUnderCRM
                                                    CheckedList1.Items[4].Selected, //IncludeCallBack
                                                    CheckedList1.Items[5].Selected,//IncludeCrawler
                                                    string.Empty,
                                                    ipAddresses,
                                                    portalSettings.PortalID);

                        if ( MonitoringTrace.Sw.TraceVerbose && monitorData != null )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring RadGrid1_NeedDataSource Rows.Count: {0}",monitorData.Rows.Count),MonitoringTrace.Sw.Info);
                        if ( monitorData == null )
                        {
                            LabelNoData.Visible     =   true;
                            RadGrid1.DataSource     =   null;
                            RadChart1.DataSource    =   null;
                            RadChart1.Clear();
                            return;
                        }
                        TransformDataTable(monitorData);
                        Cache2.InsertMinutes(key,monitorData,15);
                    }
                    RadGrid1.DataSource		        =   monitorData;
					LabelNoData.Visible			    =   false;
		            if ( MonitoringTrace.Sw.TraceVerbose )
                       Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring RadGrid1_NeedDataSource Binding reDraw: {0}.",redraw),MonitoringTrace.Sw.Info);
                    //Prepare RadGraph and bind it if necessary
                    if ( redraw )
                    {
                        RadChart1.DataSource        =   null;
                        if ( FindChartType(monitorData) )
                        {
			                if ( MonitoringTrace.Sw.TraceVerbose )
                               Trace2.WriteLine("[V]Monitoring RadGrid1_NeedDataSource Binding RadChart BEG.",MonitoringTrace.Sw.Info);
                            RadChart1.DataSource        =   monitorData;
                            RadChart1.DataBind();
                            //Doesn't work with RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.RotationAngle ???
                            if ( RadChart1.Series[0].Type != ChartSeriesType.Pie )
                                foreach(ChartAxisItem it in RadChart1.PlotArea.XAxis.Items)
                                {
                                    it.Appearance.RotationAngle = 45F;
                                }
			                    if ( MonitoringTrace.Sw.TraceVerbose )
                               Trace2.WriteLine("[V]Monitoring RadGrid1_NeedDataSource Binding RadChart END.",MonitoringTrace.Sw.Info);
                        }
                    }
                }
				catch(Exception ex)
				{
					if ( MonitoringTrace.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Monitoring RadGrid1_NeedDataSource ex:{0}",ex),MonitoringTrace.Sw.Info);
                    throw;
				}
			if ( MonitoringTrace.Sw.TraceVerbose )
               Trace2.WriteLine("[V]Monitoring RadGrid1_NeedDataSource END.",MonitoringTrace.Sw.Info);
			}
		}

        DataTable TransformDataTable(DataTable monitorData)
        {
            int selReportTp                     =   int.Parse(cboReportType.SelectedValue);

            bool tpInPageId                     =   false;
            if ( (selReportTp == 8 ) && monitorData.Columns.Contains(MNSTR.stritemid) )
                tpInPageId                      =   true;
            if ( tpInPageId )
                monitorData.Columns.Add(MNSTR.strentitytypename,typeof(string));
            bool tpCode                         =   monitorData.Columns.Contains(MNSTR.strtypecode);
            if (tpCode)
                monitorData.Columns.Add(MNSTR.strtypename,typeof(string));
            bool crmuid                         =   monitorData.Columns.Contains(MNSTR.strcrmuserid);
            if ( crmuid )
                monitorData.Columns.Add(MNSTR.strcrmusername,typeof(string));
            bool crmitem                        =   monitorData.Columns.Contains(MNSTR.strcrmitemid);
            if (crmitem)
                monitorData.Columns.Add(MNSTR.strcrmitemname,typeof(string));
            bool webuserid                        =   monitorData.Columns.Contains(MNSTR.strwebuserid);
            if (webuserid)
                monitorData.Columns.Add(MNSTR.strwebusername,typeof(string));
            
            for ( int i=0 ; i < monitorData.Rows.Count ; i++ )
            {
                DataRow rw                      =   monitorData.Rows[i];
                int entityTypeCode             =   -1;
                string entityName               =   string.Empty;
                if ( tpInPageId )
                {
                    entityTypeCode             =   (int)rw[MNSTR.stritemid];
                    entityName                  =   CRMWrapper.CRMUtil.TypeName(entityTypeCode);
                    if (MonitoringTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring TransformDataTable entityTypeCode: {0}",entityTypeCode), MonitoringTrace.Sw.Info);
                    rw[MNSTR.strentitytypename] =   entityName;
                }

                int typeCode                    =   -1;
                string userEntityName           =   string.Empty;
                if ( tpCode )
                {
                    typeCode                    =   (int)rw[MNSTR.strtypecode];
                    userEntityName              =   CRMWrapper.CRMUtil.TypeName(typeCode);
                    if (MonitoringTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring TransformDataTable typecode: {0}",typeCode), MonitoringTrace.Sw.Info);
                    rw[MNSTR.strtypename]       =   userEntityName;
                }
                
                // CRM item
                if ( crmitem )
                {
                    Guid CrmId                          =   (Guid)rw[MNSTR.strcrmitemid];
                    if (MonitoringTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring TransformDataTable CrmId: '{0}'",CrmId), MonitoringTrace.Sw.Info);
                    if ( CrmId != Guid.Empty )
                    {
                        if ( !tpInPageId )
                        {
                            entityTypeCode              =   (int)rw[MNSTR.stritemid];
                            entityName                  =   CRMWrapper.CRMUtil.TypeName(entityTypeCode);
                        }
                        if (MonitoringTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring TransformDataTable CrmId: {0}, tpName: {1}",CrmId,entityName), MonitoringTrace.Sw.Info);
                        if ( CrmItems.ContainsKey(CrmId) )
                            rw[MNSTR.strcrmitemname]    =   CrmItems[CrmId];
                        else
                        {
                            DynEntity dyn               =   new DynEntity(Wrapper,entityName,CrmId);
                            if ( dyn.adminRetrieve() )
                            {
                                string val              =   dyn.PrimaryFieldStringValue;
                                CrmItems.Add(CrmId,val);
                                rw[MNSTR.strcrmitemname]=   val;
                            }
                        }
                    }
                }
                // CRM user  id
                if ( ( typeCode != -1 ) && crmuid )
                {
                    Guid CrmId                          =   (Guid)rw[MNSTR.strcrmuserid];
                    if (MonitoringTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring TransformDataTable strcrmuserid: '{0}'",CrmId), MonitoringTrace.Sw.Info);
                    if ( CrmId != Guid.Empty )
                    {
                        if (MonitoringTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring TransformDataTable crmuserid: {0}",CrmId), MonitoringTrace.Sw.Info);
                        if ( CrmUsers.ContainsKey(CrmId) )
                            rw[MNSTR.strcrmusername]    =   CrmUsers[CrmId];
                        else
                        {
                            DynEntity dyn               =   new DynEntity(Wrapper,userEntityName,CrmId);
                            if ( dyn.adminRetrieve() )
                            {
                                string val              =   dyn.PrimaryFieldStringValue;
                                CrmUsers.Add(CrmId,val);
                                rw[MNSTR.strcrmusername]=   val;
                            }
                        }
                    }
                    else  rw[MNSTR.strcrmusername] = strAnonymous;

                }
            
                // Just to insert anonymous
                if ( webuserid )
                {
                    Guid CrmId                          =   (Guid)rw[MNSTR.strwebuserid];
                    if (MonitoringTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring TransformDataTable strwebuserid: '{0}'",CrmId), MonitoringTrace.Sw.Info);
                    if ( CrmId != Guid.Empty )
                    {
                        // TBD, normally this is same name as CrmId
                    }
                    else  rw[MNSTR.strwebusername] = strAnonymous;

                }
            }

            if (MonitoringTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring TransformDataTable END count: {0}.",monitorData.Rows.Count), MonitoringTrace.Sw.Info);
            return monitorData;
        }

        int selReportTp     =   -1;
        void RadChart1_ItemDataBound(object sender, Telerik.Charting.ChartItemDataBoundEventArgs e)
        {
            if ( selReportTp == -1 )
                selReportTp     =   int.Parse(cboReportType.SelectedValue);
            if (MonitoringTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring RadChart1_ItemDataBound BEG cboReportType: {0}", selReportTp), MonitoringTrace.Sw.Info);
                // 1 "Page Popularity":SELECT wtt.TabName, Requests = count(*), LastRequest = max(ActivityTime) ' 
				// 2 "Most Active Web Users": SELECT adnu.UserName, Actions = count(*), LastAction = max(ActivityTime) ' +
                // 3 most viewed items : SELECT adnm.ItemID, Actions = count(*), LastAction = max(ActivityTime)
                // 4 most viewed CRM items: SELECT adnm.ItemID, adnm.CrmItemID, Actions = count(*), LastAction = max(ActivityTime)
                // 5 "Page Views By Day": SELECT Date = convert(varchar,ActivityTime,102), Views = count(*), Visitors = count(distinct UserHostAddress), Users = count(distinct UserID), CrmUsers = count(distinct CrmUserID) 
				// 6 "Page Views By Browser Type": 'SELECT BrowserType, ''Views'' = count(*), ''LastAction'' = max(ActivityTime) ' +
				// 7 "Most Active Crm Users": SELECT adnm.UserField as UserName, Actions = count(*), LastAction = max(ActivityTime) '

            switch (selReportTp)
            {
                case 5:
                    e.SeriesItem.ActiveRegion.Tooltip = string.Format("Visitors : {0}, Users: {1}, CrmUsers: {2}",
                        ((DataRowView)e.DataItem)[MNSTR.strvisitors],
                        ((DataRowView)e.DataItem)[MNSTR.strwebusers],
                        ((DataRowView)e.DataItem)[MNSTR.strcrmusers]);
                    break;
                case 1:
                    e.SeriesItem.ActiveRegion.Tooltip = string.Format("Last request: {0}",((DataRowView)e.DataItem)[MNSTR.strlastrequest]);
                    break;
                case 2:
                case 3:
                case 4:
                case 6:
                case 7:
                    e.SeriesItem.ActiveRegion.Tooltip = string.Format("Last action: {0}",((DataRowView)e.DataItem)[MNSTR.strlastaction].ToString());
                    break;
            }
        }

        void RadGrid1_ItemCommand(object source,GridCommandEventArgs e)
        {
            if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[[V]ExportOrders RadGrid1_ItemCommand BEG CommandName: {0}.", e.CommandName),MonitoringTrace.Sw.Info);
            if ( e.CommandName == RadGrid.ExportToExcelCommandName )
            {
                BtnExport2XL();
                e.Canceled  =   true;
                return;
            }
            
            if ( e.CommandName == RadGrid.ExportToWordCommandName )
            {
                BtnExport2Wrd();
                e.Canceled  =   true;
                return;
            }
            
            if ( e.CommandName == RadGrid.ExportToCsvCommandName )
            {
                BtnExport2Csv();
                e.Canceled  =   true;
                return;
            }
            if ( e.CommandName == RadGrid.ExportToPdfCommandName )
            {
                BtnExport2Pdf();
                e.Canceled  =   true;
                return;
            }
            if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[[V]ExportOrders RadGrid1_ItemCommand END CommandName: {0}.", e.CommandName),MonitoringTrace.Sw.Info);
        }

        /// <summary>
        /// Just here to hide the create button of Telerik CommandItem
        /// </summary>
        void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridCommandItem)
            {
                // the link button
                LinkButton btn  =   (LinkButton)e.Item.FindControl("InitInsertButton");
                if ( btn != null )
                    btn.Visible =   false;
                //the image
                Control img     =   e.Item.FindControl("AddNewRecordButton");
                if ( img != null )
                    img.Visible =   false;
            }
        }

        void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
        {
            /*
             4->   adnm.ItemID, adnm.CrmItemID, ''Actions'' = count(*), ''LastAction
             7->   adnm.UserField as UserName, ''Actions'' = count(*), ''LastAction'' = max(ActivityTime)
            
            */
            
            if ( !(e.Column is GridEditableColumn) )
                return;
            if (MonitoringTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring RadGrid1_ColumnCreated BEG HeaderText: {0}, ColumnType: {1}, DataTypeName: {2}", e.Column.HeaderText,e.Column.ColumnType,e.Column.DataTypeName), MonitoringTrace.Sw.Info);
            string colName                  =   e.Column.HeaderText; //default
            int selreport                   =   int.Parse(cboReportType.SelectedValue);
                        
            if ( e.Column is GridBoundColumn )
            {
                colName                     =   ((GridBoundColumn)e.Column).DataField.ToLower();
                // clipping on values ??? , avoid typecode because we need to transform it on ItemGridDataBound
                //if ( ( colName != MNSTR.strtypecode ) || ( colName != MNSTR.strcrmuserid) ||  ( colName != MNSTR.strcrmitemid) )
                //    ((GridBoundColumn)e.Column).DataFormatString = "<nobr>{0}</nobr>";   
            }
            else if (e.Column is GridCheckBoxColumn)
                colName = ((GridCheckBoxColumn)e.Column).DataField.ToLower();
            else if (e.Column is GridTemplateColumn)
                colName = ((GridTemplateColumn)e.Column).DataField.ToLower();
            else if (e.Column is GridDropDownColumn)
                colName = ((GridDropDownColumn)e.Column).DataField.ToLower();
            
            if (MonitoringTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring RadGrid1_ColumnCreated colName: {0}, HeaderText: {1}", colName, e.Column.HeaderText), MonitoringTrace.Sw.Info);
            string newName                      =   string.Empty;
            bool display                        =   true;
            switch (colName)
            {
                case MNSTR.strid:
                    newName                     =   LocalizeHelper.Localize(MNSTR.id, "Id");
                    display                     =   Settings[MNSTR.id].ToBool();
                    e.Column.HeaderStyle.Width  =   new Unit("50px");
                    break;
                case MNSTR.strtypecode:
                    //newName                     =   LocalizeHelper.Localize(MNSTR.typecode, "Entity");
                    display                     =   false;
                    break;
                case MNSTR.strtypename:
                    newName                     =   LocalizeHelper.Localize(MNSTR.typecode, "Entity");
                    display                     =   Settings[MNSTR.typecode].ToBool() || (selreport == 0) || (selreport == 8) || (selreport == 4) ;
                    e.Column.HeaderStyle.Width  =   new Unit("80px");
                    break;
                case MNSTR.strwebuserid:
                    newName                     =   LocalizeHelper.Localize(MNSTR.webuserid, "Web User Id");
                    display                     =   false;
                    break;
                case MNSTR.strwebusername:
                    newName                     =   LocalizeHelper.Localize(MNSTR.webusername, "Web User");
                    e.Column.HeaderStyle.Width  =   new Unit("200px");
                    display                     =   Settings[MNSTR.webuserid].ToBool() || selreport == 0 || selreport == 8 ;
                    break;
                case MNSTR.strcrmuserid:
                    newName                     =   LocalizeHelper.Localize(MNSTR.crmuserid, "Crm User Id");
                    display                     =   false;
                    break;
                case MNSTR.strcrmusername:
                    newName                     =   LocalizeHelper.Localize(MNSTR.crmusername, "Crm User");
                    e.Column.HeaderStyle.Width  =   new Unit("200px");
                    display                     =   Settings[MNSTR.crmuserid].ToBool() || (selreport == 0) || (selreport == 8);
                    break;
                case MNSTR.strportalid:
                    newName                     =   LocalizeHelper.Localize(MNSTR.portalid, "Portal Id");
                    e.Column.HeaderStyle.Width  =   new Unit("50px");
                    display                     =   Settings[MNSTR.portalid].ToBool();
                    break;
                case MNSTR.strpageid:
                    newName                     =   LocalizeHelper.Localize(MNSTR.pageid, "Page Id");
                    e.Column.HeaderStyle.Width  =   new Unit("50px");
                    display                     =   Settings[MNSTR.pageid].ToBool();
                    break;
                case MNSTR.strtabname:
                    newName                     =   LocalizeHelper.Localize(MNSTR.tabname, "Page Name");
                    e.Column.HeaderStyle.Width  =   new Unit("150px");
                    GridColumn pgCol            =   RadGrid1.MasterTableView.GetColumnSafe(MNSTR.pageid);
                    // try to set PageName near pageid
                    if ( (pgCol!= null ) && pgCol.Visible && pgCol.OrderIndex <  RadGrid1.MasterTableView.Columns.Count )
                        RadGrid1.MasterTableView.SwapColumns(pgCol.OrderIndex+1,e.Column.OrderIndex);
                    display                     =   Settings[MNSTR.tabname].ToBool();
                    break;
                case MNSTR.strmoduleid:
                    newName                     =   LocalizeHelper.Localize(MNSTR.moduleid, "Module Id");
                    e.Column.HeaderStyle.Width  =   new Unit("50px");
                    display                     =   Settings[MNSTR.moduleid].ToBool();
                    break;
                case MNSTR.stritemid:
                    newName                     =   LocalizeHelper.Localize(MNSTR.itemid, "Item Id");
                    e.Column.HeaderStyle.Width  =   new Unit("50px");
                    display                     =   Settings[MNSTR.itemid].ToBool() ||  (selreport == 4 ) ;
                    break;
                case MNSTR.strentitytypename:
                    newName                     =   LocalizeHelper.Localize(MNSTR.typecode, "Entity");
                    e.Column.HeaderStyle.Width  =   new Unit("80px");
                    break;
                case MNSTR.strcrmitemid:
                    e.Column.HeaderStyle.Width  =   new Unit("50px");
                    display                     =   false;
                    break;
                case MNSTR.strcrmitemname:
                    newName                     =   LocalizeHelper.Localize(MNSTR.crmitemname, "Crm Item");
                    e.Column.HeaderStyle.Width  =   new Unit("200px");
                    display                     =   Settings[MNSTR.crmitemid].ToBool() || (selreport == 4)|| (selreport == 0) || (selreport == 8);
                    GridColumn crmIdCol         =   RadGrid1.MasterTableView.GetColumnSafe(MNSTR.strentitytypename);
                    // try to set strentitytypename before strcrmitemid
                    if ( (crmIdCol!= null ) && crmIdCol.OrderIndex <  RadGrid1.MasterTableView.Columns.Count )
                        RadGrid1.MasterTableView.SwapColumns(crmIdCol.OrderIndex+1,e.Column.OrderIndex);
                    break;
                case MNSTR.stractivitytime:
                    newName                     =   LocalizeHelper.Localize(MNSTR.activitytime, "Activity Time");
                    e.Column.HeaderStyle.Width  =   new Unit("150px");
                    e.Column.ItemStyle.Wrap     =   false;
                    display                     =   Settings[MNSTR.activitytime].ToBool();
                    break;
                case MNSTR.stractivitytype:
                    newName                     =   LocalizeHelper.Localize(MNSTR.activitytype, "Activity Type");
                    e.Column.HeaderStyle.Width  =   new Unit("150px");
                    display                     =   Settings[MNSTR.activitytype].ToBool();
                    break;
                case MNSTR.strreferrer:
                    newName                     =   LocalizeHelper.Localize(MNSTR.referrer, "Url Referer");
                    e.Column.HeaderStyle.Width  =   new Unit("300px");
                    display                     =   Settings[MNSTR.referrer].ToBool();
                    break;
                case MNSTR.struseragent:
                    newName                     =   LocalizeHelper.Localize(MNSTR.useragent, "User Agent");
                    e.Column.HeaderStyle.Width  =   new Unit("300px");
                    e.Column.ItemStyle.Wrap     =   false;
                    display                     =   Settings[MNSTR.useragent].ToBool();
                    break;
                case MNSTR.struserhostaddress:
                    newName                     =   LocalizeHelper.Localize(MNSTR.userhostaddress, "User Host");
                    e.Column.HeaderStyle.Width  =   new Unit("100px");
                    display                     =   Settings[MNSTR.userhostaddress].ToBool();
                    break;
                case MNSTR.strbrowsertype:
                    newName                     =   LocalizeHelper.Localize(MNSTR.browsertype, "Browser Type");
                    e.Column.HeaderStyle.Width  =   new Unit("150px");
                    display                     =   Settings[MNSTR.browsertype].ToBool() || (selreport == 6);
                    break;
                case MNSTR.strbrowsername:
                    newName                     =   LocalizeHelper.Localize(MNSTR.browsername, "Browser Name");
                    e.Column.HeaderStyle.Width  =   new Unit("100px");
                    display                     =   Settings[MNSTR.browsername].ToBool() || (selreport == 6);
                    break;
                case MNSTR.strbrowserversion:
                    newName                     =   LocalizeHelper.Localize(MNSTR.browserversion, "Browser version");
                    e.Column.HeaderStyle.Width  =   new Unit("50px");
                    display                     =   Settings[MNSTR.browserversion].ToBool();
                    break;
                case MNSTR.strbrowserplatform:
                    newName                     =   LocalizeHelper.Localize(MNSTR.browserplatform, "Browser Platform");
                    e.Column.HeaderStyle.Width  =   new Unit("150px");
                    display                     =   Settings[MNSTR.browserplatform].ToBool();
                    break;
                case MNSTR.strbrowserisaol:
                    newName                     =   LocalizeHelper.Localize(MNSTR.isundercrm, "UnderCRM");
                    e.Column.HeaderStyle.Width  =   new Unit("50px");
                    display                     =   Settings[MNSTR.browserisaol].ToBool();
                    break;
                case MNSTR.struserfield:
                    newName                     =   LocalizeHelper.Localize(MNSTR.userfield, "User Field");
                    e.Column.HeaderStyle.Width  =   new Unit("300px");
                    display                     =   Settings[MNSTR.userfield].ToBool();
                    break;
                case MNSTR.strusername:
                    newName                     =   LocalizeHelper.Localize(MNSTR.username, "User Name");
                    e.Column.HeaderStyle.Width  =   new Unit("200px");
                    display                     =   Settings[MNSTR.username].ToBool() || (selreport == 7);
                    break;
                case MNSTR.strviews:
                    newName                     =   LocalizeHelper.Localize(MNSTR.views, "Total views");
                    e.Column.HeaderStyle.Width  =   new Unit("100px");
                    break;
                case MNSTR.strvisitors:
                    newName                     =   LocalizeHelper.Localize(MNSTR.visitors, "Total visitors");
                    e.Column.HeaderStyle.Width  =   new Unit("100px");
                    break;
                case MNSTR.stractions:
                    newName                     =   LocalizeHelper.Localize(MNSTR.actions, "Total visitors");
                    e.Column.HeaderStyle.Width  =   new Unit("100px");
                    break;
                case MNSTR.strlastaction:
                    newName                     =   LocalizeHelper.Localize(MNSTR.lastaction, "Last action");
                    e.Column.HeaderStyle.Width  =   new Unit("200px");
                    break;
                case MNSTR.strrequests:
                    newName                     =   LocalizeHelper.Localize(MNSTR.requests, "Total requests");
                    e.Column.HeaderStyle.Width  =   new Unit("100px");
                    break;
                case MNSTR.strlastrequest:
                    newName                     =   LocalizeHelper.Localize(MNSTR.lastrequest, "Last request");
                    e.Column.HeaderStyle.Width  =   new Unit("200px");
                    break;
                case MNSTR.strwebusers:
                    newName                     =   LocalizeHelper.Localize(MNSTR.webusers, "Total Web users");
                    e.Column.HeaderStyle.Width  =   new Unit("100px");
                    break;
                case MNSTR.strcrmusers:
                    newName                     =   LocalizeHelper.Localize(MNSTR.crmusers, "Total Crm users");
                    e.Column.HeaderStyle.Width  =   new Unit("100px");
                    break;
                case MNSTR.strdays:
                    newName                     =   LocalizeHelper.Localize(MNSTR.strdays, "Days");
                    e.Column.HeaderStyle.Width  =   new Unit("100px");
                    break;
                case MNSTR.strtime:
                    newName                     =   LocalizeHelper.Localize(MNSTR.Time, "Numeric time");
                    e.Column.HeaderStyle.Width  =   new Unit("100px");
                    break;
                case MNSTR.strcount:
                    newName                     =   LocalizeHelper.Localize(MNSTR.Count, "Event Count");
                    break;
                default:
                    if (MonitoringTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring RadGrid1_ColumnCreated NOT FOUND colName: {0}, HeaderText: {1}.", 
                            colName, e.Column.HeaderText), MonitoringTrace.Sw.Info);
                    break;
            }
            // Originally it was e.Column.Display but its impossible to resize a column when using display=false columns
            e.Column.Visible                    =   display;
            if (newName != string.Empty)
            {
                newName.Replace(" ",StStr.HTML_SPACE); // force non breakable space for header text
                e.Column.HeaderText = newName;
            }
            if (MonitoringTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring RadGrid1_ColumnCreated END colName: {0}, new HeaderText: [{1}], display: {2}, HeaderStyle.Width: {3}", 
                    new object[]{colName, newName,display,e.Column.HeaderStyle.Width}), MonitoringTrace.Sw.Info);
        }

        void InitGridParam0()
        {
            RadGrid1.AllowCustomPaging                                      =   true;
            RadGrid1.ClientSettings.Scrolling.AllowScroll                   =   Settings[MNSTR.AllowScrolling].ToBool();
            if ( RadGrid1.ClientSettings.Scrolling.AllowScroll )
                RadGrid1.ClientSettings.Scrolling.ScrollHeight              =   Settings[MNSTR.ScrollingHeight].ToUnit();
            if ( Settings[MNSTR.OptimizeGrid].ToBool() )
            {
                RadGrid1.ShowGroupPanel                                     =   false;
                RadGrid1.AllowFilteringByColumn                             =   false; 
                RadGrid1.ClientSettings.AllowDragToGroup                    =   false;
                RadGrid1.ClientSettings.Scrolling.EnableVirtualScrollPaging =   false;
            }
            else
            {
			    RadGrid1.VirtualItemCount                                   =   10000;
                RadGrid1.ShowGroupPanel                                     =   true;
                RadGrid1.AllowFilteringByColumn                             =   true; 
                RadGrid1.ClientSettings.AllowDragToGroup                    =   true;
                RadGrid1.ClientSettings.Scrolling.EnableVirtualScrollPaging =   true;
            }
        }

        /// <summary>
        /// Add 2 columns to table to transform dates in doubles and add actions each step
        /// </summary>
        void FillGraph(DataTable MonitorData,ChartSeries chartS1)
        {
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring FillGraph BEG MonitorData Rows Count: {0}",MonitorData.Rows.Count),MonitoringTrace.Sw.Info);
            if ( MonitorData.Rows.Count < 1 )
                return;
            const double hourStep           =   1 / 24.0;
            const double minuteStep         =   hourStep / 60;
            const double fiveMinuteStep     =   minuteStep * 5;
            
            int selReportTp                 =   int.Parse(cboReportType.SelectedValue); //0 or 8

            double startTime                =   RadDateStart.SelectedDate.Value.ToOADate();
            double endTime                  =   RadDateEnd.SelectedDate.Value.ToOADate();
            long size                       =   RadDateEnd.SelectedDate.Value.Ticks-RadDateStart.SelectedDate.Value.Ticks;
            TimeSpan sp                     =   TimeSpan.FromTicks(size);
            int nbdays                      =   sp.Days;
            double step                     =   1;
            if (nbdays <= 1)
            {
                step                        =   fiveMinuteStep;
                if (startTime == endTime)
                {
                    DateTime dt             =   RadDateStart.SelectedDate.Value;
                    DateTime sdt            =   new DateTime(dt.Year,dt.Month,dt.Day,0,0,0);
                    DateTime edt            =   new DateTime(dt.Year,dt.Month,dt.Day,23,59,59);
			        if ( MonitoringTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring FillGraph adjusting dates start: {0}, end: {1}",sdt.ToLongTimeString(),edt.ToLongTimeString()),MonitoringTrace.Sw.Info);
                    startTime                =   sdt.ToOADate();
                    endTime                  =   edt.ToOADate();
                }
            }
            int idx                         =   0;
            int idxmax                      =   MonitorData.Rows.Count;
            DataRow rw                      =   MonitorData.Rows[0];
            double maxDate                  =   ((DateTime)rw[MNSTR.stractivitytime]).ToOADate();;
            rw                              =   MonitorData.Rows[MonitorData.Rows.Count-1];
            double minDate                  =   ((DateTime)rw[MNSTR.stractivitytime]).ToOADate();;
            int count                       =   0;
            DateTime prevDate               =   DateTime.MaxValue;
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring FillGraph nbDays: {0},minDate: {1}, maxDate: {2}",nbdays,minDate,maxDate),MonitoringTrace.Sw.Info);
            // table is ordered by activtytime DESC
            for (double currentTime = maxDate; currentTime >= minDate && idx < idxmax ; currentTime -= step)
            {
                while (idx < idxmax)
                {
                    rw                          =   MonitorData.Rows[idx];
                    double tm                   =   ((DateTime)rw[MNSTR.stractivitytime]).ToOADate();
                    if ( MonitoringTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring FillGraph current: {0}, tm: {1}, idx: {2}, Count: {3}, minDate: {4}, maxDate: {5}",
                            new object[]{currentTime,tm,idx,count,minDate,maxDate}),MonitoringTrace.Sw.Info);
                    if ( tm >= (currentTime - step) && tm > minDate )
                        count++;
                    else 
                    {
                        if ( MonitoringTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring FillGraph Created current: {0}, tm: {1}, idx: {2}, Count: {3}, minDate: {4}, maxDate: {5}",
                                new object[]{currentTime,tm,idx,count,minDate,maxDate}),MonitoringTrace.Sw.Info);
                        ChartSeriesItem item        =   new ChartSeriesItem();
                        if (nbdays > 1)
                        {
                                item.Name                   =   prevDate.ToShortDateString().Replace('/','_');
                                item.ActiveRegion.Tooltip   =   prevDate.ToShortDateString();
                        }
                        else    
                        {
                                item.Name                   =   prevDate.ToLongTimeString().Replace('/','_');
                                item.ActiveRegion.Tooltip   =   prevDate.ToLongDateString();
                        }
                        item.Label.TextBlock.Text   =   count.ToString();//string.Format("{0}-{1}",nbdays,count);
                        item.XValue                 =   currentTime;
                        item.YValue                 =   count;
                        chartS1.Items.Add(item);
                        // NOT available ADNPage.AddToolTipTarget(item.Name);
                        // to avoid missing zero count dates names
                        if (count == 0)
                            prevDate                        =   (DateTime)rw[MNSTR.stractivitytime];   
                        // reset counter
                        count                       =   0;
                        break;
                    }
                    idx++;
                    prevDate                        =   (DateTime)rw[MNSTR.stractivitytime];   
                }
            }
            RadChart1.PlotArea.XAxis.AxisLabel.Visible  =   true;
            RadChart1.PlotArea.XAxis.AxisLabel.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.BottomRight;
            //RadChart1.PlotArea.XAxis.AxisLabel.TextBlock.Visible    =   true;
            //RadChart1.PlotArea.XAxis.AxisLabel.TextBlock.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
            if (nbdays <= 1)
            {
                RadChart1.PlotArea.XAxis.AxisLabel.TextBlock.Text                               =   string.Format("{0:u}",RadDateStart.SelectedDate.Value);
                RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.Position.AlignedPosition    =   Telerik.Charting.Styles.AlignedPositions.Center;
                RadChart1.PlotArea.XAxis.Appearance.TextAppearance.Position.AlignedPosition     =   Telerik.Charting.Styles.AlignedPositions.Center;
                RadChart1.PlotArea.XAxis.Appearance.ValueFormat                                 =   Telerik.Charting.Styles.ChartValueFormat.ShortTime;
                RadChart1.PlotArea.XAxis.AddRange(startTime, endTime, step);
                RadChart1.PlotArea.XAxis.LabelStep              =   12;
            }
            else
            {
                RadChart1.PlotArea.XAxis.AxisLabel.TextBlock.Text                               =   string.Format("{0:u} to {1:u}",
                                                                                                    RadDateStart.SelectedDate.Value,RadDateEnd.SelectedDate.Value);
                RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.Position.AlignedPosition    =   Telerik.Charting.Styles.AlignedPositions.Center;
                RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.RotationAngle               =   45F;
                RadChart1.PlotArea.XAxis.Appearance.ValueFormat                                 =   Telerik.Charting.Styles.ChartValueFormat.ShortDate;
                RadChart1.PlotArea.XAxis.AddRange(minDate, maxDate, step);
            }
            foreach(ChartAxisItem it in RadChart1.PlotArea.XAxis.Items)
            {
                it.Appearance.RotationAngle = 45F;
            }

            if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring FillGraph Chart items Count: {0}",chartS1.Items.Count),MonitoringTrace.Sw.Info);
        }

        /// <summary>
        /// Prespare radGraph according parameters
        /// Return indicator for binding radGraph to MonitorData
        /// </summary>
        bool FindChartType(DataTable MonitorData)
        {
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring FindChartType BEG ReportType: {0}, GraphType: [{1}]",
                    cboReportType.SelectedItem.Value,CbGraphType.SelectedValue.ToString()),MonitoringTrace.Sw.Info);
            RadChart1.Clear();
            RadChart1.ChartTitle.TextBlock.Text                 =   string.Format("{0} : {1}",portalSettings.PortalName,cboReportType.SelectedItem.Text);
            ChartSeriesType chartTp                             =   (ChartSeriesType)int.Parse(CbGraphType.SelectedValue);
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring FindChartType ChartType: {0}",chartTp),MonitoringTrace.Sw.Info);

            // display datas with graph
            RadChart1.PlotArea.DataTable.Visible                =   Settings[MNSTR.DataTable].ToBool();
            ChartSeries chartS1                                 =   new ChartSeries();
            // default when only one serie
            chartS1.Name                                        =   cboReportType.SelectedItem.Text;
            if ( chartTp == ChartSeriesType.Pie )
                chartS1.Appearance.LegendDisplayMode            =   ChartSeriesLegendDisplayMode.ItemLabels;
            bool ret                                            =   true; // binding flag for radgraph
            ChartSeries chartS2                                 =   null;
            ChartSeries chartS3                                 =   null;
            ChartSeries chartS4                                 =   null;
			switch (cboReportType.SelectedItem.Value)
			{
				//case "Detailed Host Address Log":
				case "9":
				//case "Detailed Site Log":
				case "0":
                    RadGrid1.VirtualItemCount                       =   MonitorData.Rows.Count;
                    RadChart1.PlotArea.DataTable.Visible            =   false;
                    chartS1.Type                                    =   ChartSeriesType.Area;
                    chartS1.Appearance.ShowLabels                   =   false;
                    RadChart1.Appearance.TextQuality                =   Telerik.Charting.Styles.TextQuality.AntiAlias;
                    RadChart1.PlotArea.XAxis.LayoutMode             =   Telerik.Charting.Styles.ChartAxisLayoutMode.Inside;
                    RadChart1.PlotArea.XAxis.AutoScale              =   false;
                    //RadChart1.PlotArea.XAxis.Appearance.MajorGridLines.Visible  =   false;
                    RadChart1.PlotArea.YAxis.IsZeroBased            =   false;
                    chartS1.Name                                    =   LocalizeHelper.Localize(MNSTR.actions, MNSTR.stractions);
                    FillGraph(MonitorData,chartS1);
                    ret                                             =   false;
					break;

                // detailled CRM items
				case "8":
                    RadGrid1.VirtualItemCount                       =   MonitorData.Rows.Count;
                    RadChart1.PlotArea.DataTable.Visible            =   false;
                    chartS1.Type                                    =   ChartSeriesType.Area;
                    chartS1.Appearance.ShowLabels                   =   false;
                    RadChart1.Appearance.TextQuality                =   Telerik.Charting.Styles.TextQuality.AntiAlias;
                    RadChart1.PlotArea.XAxis.LayoutMode             =   Telerik.Charting.Styles.ChartAxisLayoutMode.Inside;
                    RadChart1.PlotArea.XAxis.AutoScale              =   false;
                    //RadChart1.PlotArea.XAxis.Appearance.MajorGridLines.Visible  =   false;
                    RadChart1.PlotArea.YAxis.IsZeroBased            =   false;
                    chartS1.Name                                    =   LocalizeHelper.Localize(MNSTR.actions, MNSTR.stractions);
                    FillGraph(MonitorData,chartS1);
                    ret                                             =   false;
					break;

                //case "Page Popularity":SELECT wtt.TabName, Requests = count(*), LastRequest = max(ActivityTime) ' 
				case "1":
                    chartS1.Type                                    =   chartTp;
                    if ( chartS1.Type != ChartSeriesType.Pie )
                    {
                        RadChart1.PlotArea.YAxis.AxisMode   =    ChartYAxisMode.Extended;
                        RadChart1.PlotArea.XAxis.DataLabelsColumn = MNSTR.strtabname;
                        RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.RotationAngle = 45F;
                    }
                    else
                        chartS1.DataLabelsColumn = MNSTR.strtabname;
                    chartS1.DataYColumn                             =   MNSTR.strrequests;
                    break;

				//case "Most Active Web Users": SELECT adnu.UserName, Actions = count(*), LastAction = max(ActivityTime) ' +
				case "2":
                    chartS1.Type                                    =   chartTp;
                    if ( chartS1.Type != ChartSeriesType.Pie)
                    {
                        RadChart1.PlotArea.YAxis.AxisMode   =    ChartYAxisMode.Extended;
                        RadChart1.PlotArea.XAxis.DataLabelsColumn   =   MNSTR.strusername;
                        RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.RotationAngle = 45F;
                    }
                    else chartS1.DataLabelsColumn                   =   MNSTR.strusername;
                    chartS1.DataYColumn                             =   MNSTR.stractions;
					break;
                // most viewed items : SELECT adnm.ItemID, Actions = count(*), LastAction = max(ActivityTime)
				case "3":
                    chartS1.Type                                    =   chartTp;
                    if (chartS1.Type != ChartSeriesType.Pie)
                    {
                        RadChart1.PlotArea.YAxis.AxisMode   =    ChartYAxisMode.Extended;
                        RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.RotationAngle = 45F;
                        RadChart1.PlotArea.XAxis.DataLabelsColumn   =   MNSTR.stritemid;
                        RadChart1.PlotArea.XAxis.AxisLabel.TextBlock.Text = LocalizeHelper.Localize(MNSTR.actions, MNSTR.stractions);
                    }
                    else chartS1.DataLabelsColumn                   =   MNSTR.stritemid;
                    chartS1.DataYColumn                             =   MNSTR.stractions;
					break;

                // most viewed CRM items: SELECT adnm.ItemID, adnm.CrmItemID, Actions = count(*), LastAction = max(ActivityTime)
				case "4":
                    chartS1.Type                                    =   chartTp;
                    if (chartS1.Type != ChartSeriesType.Pie)
                    {
                        RadChart1.PlotArea.YAxis.AxisMode           =    ChartYAxisMode.Extended;
                        RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.RotationAngle = 45F;
                        RadChart1.PlotArea.XAxis.DataLabelsColumn   =   MNSTR.strcrmitemname;
                        RadChart1.PlotArea.XAxis.AxisLabel.TextBlock.Text = LocalizeHelper.Localize(MNSTR.crmitemid, MNSTR.strcrmitemid);
                    }
                    else chartS1.DataLabelsColumn                   =   MNSTR.strcrmitemname;
                    chartS1.DataYColumn                             =   MNSTR.stractions;
					break;

                //case "Page Views By Day": SELECT Date = convert(varchar,ActivityTime,102), Views = count(*), Visitors = count(distinct UserHostAddress), Users = count(distinct UserID), CrmUsers = count(distinct CrmUserID) 
				case "5":
                    RadChart1.DefaultType                           =   chartTp;
                    chartS1.Type                                    =   chartTp;
                    if (chartS1.Type != ChartSeriesType.Pie)
                    {
                        RadChart1.PlotArea.XAxis.DataLabelsColumn                           =   MNSTR.strdate;
                        RadChart1.PlotArea.XAxis.AxisLabel.TextBlock.Text                   =   LocalizeHelper.Localize(MNSTR.days,MNSTR.strdays);
                        RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.RotationAngle   =   45;
                        RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.Position.AlignedPosition    = Telerik.Charting.Styles.AlignedPositions.Top;
                    }
                    else chartS1.DataLabelsColumn                   =   MNSTR.strdate;
                    chartS1.DataYColumn                             =   MNSTR.strviews;
                    chartS1.Name                                    =   LocalizeHelper.Localize(MNSTR.views,MNSTR.strviews);
                    chartS2                                         =   new ChartSeries();
                    chartS2.Type                                    =   chartTp;
                    chartS2.DataYColumn                             =   MNSTR.strvisitors;
                    chartS2.Name                                    =   LocalizeHelper.Localize(MNSTR.visitors,MNSTR.strvisitors);
                    RadChart1.AddChartSeries(chartS2);
                    chartS3                                         =   new ChartSeries();
                    chartS3.Type                                    =   chartTp;
                    chartS3.DataYColumn                             =   MNSTR.strwebusers;
                    chartS3.Name                                    =   LocalizeHelper.Localize(MNSTR.webusers,MNSTR.strwebusers);
                    RadChart1.AddChartSeries(chartS3);
                    chartS4                                         =   new ChartSeries();
                    chartS4.Type                                    =   chartTp;
                    chartS4.DataYColumn                             =   MNSTR.strcrmusers;
                    chartS4.Name                                    =   LocalizeHelper.Localize(MNSTR.crmusers,MNSTR.strcrmusers);
                    RadChart1.AddChartSeries(chartS4);
                    
                    break;

				//case "Page Views By Browser Type": SELECT BrowserType, Views = count(*) ' +
				case "6": 
                    chartS1.Type                                    =   chartTp;
                    if ( chartS1.Type != ChartSeriesType.Pie)
                    {
                        RadChart1.PlotArea.YAxis.AxisMode   =    ChartYAxisMode.Extended;
                        RadChart1.PlotArea.XAxis.DataLabelsColumn   =   MNSTR.strbrowsertype;
                        RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.RotationAngle = 45F;
                    }
                    else chartS1.DataLabelsColumn                   =   MNSTR.strbrowsertype;
                    chartS1.DataYColumn                             =   MNSTR.strviews;
					break;

				//case "Most Active Crm Users": SELECT adnm.UserField as UserName, Actions = count(*), LastAction = max(ActivityTime) '
                case "7":
                    chartS1.Type                                    =   chartTp;
                    if ( chartS1.Type != ChartSeriesType.Pie)
                    {
                        RadChart1.PlotArea.YAxis.AxisMode   =    ChartYAxisMode.Extended;
                        RadChart1.PlotArea.XAxis.DataLabelsColumn   =   MNSTR.strusername;
                        RadChart1.PlotArea.XAxis.Appearance.LabelAppearance.RotationAngle = 45F;
                    }
                    else chartS1.DataLabelsColumn                   =   MNSTR.strusername;
                    chartS1.DataYColumn                             =   MNSTR.stractions;
					break;
			}				
            RadChart1.AddChartSeries(chartS1);
            if ( chartS2 != null )
                RadChart1.AddChartSeries(chartS2);
            if ( chartS3 != null )
                RadChart1.AddChartSeries(chartS3);
            if ( chartS3 != null )
                RadChart1.AddChartSeries(chartS3);
            if ( chartS4 != null )
                RadChart1.AddChartSeries(chartS4);
            // Bug zoom and Pie and Bar ???
            ChartSeries dumS    =   new ChartSeries(string.Empty, ChartSeriesType.Line);
            dumS.Visible        =   false;
            RadChart1.AddChartSeries(dumS);
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring FindChartType END ret: {0}, chartS1.Type: {1}.",ret,chartS1.Type),MonitoringTrace.Sw.Info);
            return ret;
        }

        protected override void OnPreRender(EventArgs e)
        {
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring OnPreRender BEG ShoudlRebind: {0}.",ShoudlRebind),MonitoringTrace.Sw.Info);
            if ( ShoudlRebind )
            {
 			    if ( MonitoringTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring OnPreRender Width: {0}, Height: {1}.",RadChart1.Width,RadChart1.Height),MonitoringTrace.Sw.Info);
               ShoudlRebind    =   false;
                ReBind();
			    if ( MonitoringTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Monitoring OnPreRender after rebind Width: {0}, Height: {1}.",RadChart1.Width,RadChart1.Height),MonitoringTrace.Sw.Info);
            }
            base.OnPreRender(e);
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring OnPreRender END.",MonitoringTrace.Sw.Info);
        }

		#region Std Overrides

        public override void Page_PreInit(object sender, EventArgs e)
		{
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring Page_PreInit BEG.",MonitoringTrace.Sw.Info);
			base.Page_PreInit(sender, e);
            string loc          =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            BtnRefresh.SkinID           =   "Update_" + loc;
            BtnReset.SkinID             =   "Reset_" + loc;
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring Page_PreInit END.",MonitoringTrace.Sw.Info);
		}
		
 		override protected void OnInit(EventArgs e)
		{
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring OnInit BEG.",MonitoringTrace.Sw.Info);
			InitializeComponent();
			base.OnInit(e);
			if ( MonitoringTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Monitoring OnInit END.",MonitoringTrace.Sw.Info);
		}
		
        private void InitializeComponent() 
		{    
			RadGrid1.NeedDataSource                         +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.ColumnCreated                          +=  new GridColumnCreatedEventHandler(RadGrid1_ColumnCreated);
            RadGrid1.ItemCreated                            +=  new GridItemEventHandler(RadGrid1_ItemCreated);
            RadGrid1.ItemCommand                            +=  new GridCommandEventHandler(RadGrid1_ItemCommand);
			Load                                            +=  new EventHandler(Monitoring_Load);
            BtnRefresh.Click                                +=  new ImageClickEventHandler(BtnRefresh_Click);
            BtnReset.Click                                  +=  new ImageClickEventHandler(BtnReset_Click);
            cboReportType.SelectedIndexChanged              +=  new RadComboBoxSelectedIndexChangedEventHandler(cboReportType_SelectedIndexChanged);
            CbGraphType.SelectedIndexChanged                +=  new RadComboBoxSelectedIndexChangedEventHandler(CbGraphType_SelectedIndexChanged);
            ThumbList.ItemDataBound                         +=  new RadComboBoxItemEventHandler(ThumbList_ItemDataBound);
            ThumbList.SelectedIndexChanged                  +=  new RadComboBoxSelectedIndexChangedEventHandler(ThumbList_SelectedIndexChanged);
            CheckedList1.SelectedIndexChanged               +=  new EventHandler(CheckedList1_SelectedIndexChanged);
            CheckedList2.SelectedIndexChanged               +=  new EventHandler(CheckedList1_SelectedIndexChanged);
            RadDateStart.TextChanged                        +=  new EventHandler(CheckedList1_SelectedIndexChanged);
            RadDateEnd.TextChanged                          +=  new EventHandler(CheckedList1_SelectedIndexChanged);
            RadChart1.ItemDataBound                         +=  new EventHandler<Telerik.Charting.ChartItemDataBoundEventArgs>(RadChart1_ItemDataBound);
            if ( Settings[MNSTR.OptimizeGrid].ToBool() )
            {
                RadGrid1.MasterTableView.EnableViewState    =   false;
            }
            if ( Settings[MNSTR.ChartWithZoom].ToBool() )
            {
                RadChart1.ClientSettings.EnableZoom         =   true;
                RadChart1.ClientSettings.ScrollMode         =   ChartClientScrollMode.Both;
                RadZoomDiv.Visible                          =   true;
            }
            else
            {
                RadChart1.ClientSettings.EnableZoom         =   false;
                RadChart1.ClientSettings.ScrollMode         =   ChartClientScrollMode.None;
                RadZoomDiv.Visible                          =   false;
            }
            RadAjaxManager aj                               =   (RadAjaxManager)Page.FindControl("RadAjaxManager1");
            if ( aj != null )
                aj.AjaxRequest                              +=  new RadAjaxControl.AjaxRequestDelegate(AjaxManager_AjaxRequest);
      }


        #endregion
    }
}